const parser = require('../parser')

module.exports = class Pieces {
  constructor(torrent) {
    // The torrent.info.pieces is a buffer that contains 20-byte SHA-1 hash of each piece.
    // And the length gives you the total number of bytes in the buffer.
    const totalPices = torrent.info.pieces.length / 20

    // 0: not requested, 1: requested, 2: received
    this._pieces = new Array(totalPices).fill(null)
    this._pieces = this._pieces.map((_, pieceIndex) => new Array(parser.blockNum(torrent, pieceIndex)).fill(0))
  }

  request (block) {
    const blockIndex = block.begin / parser.BLOCK_LEN
    this._pieces[block.index][blockIndex] = 1
  }

  receive (block) {
    const blockIndex = block.begin / parser.BLOCK_LEN
    this._pieces[block.index][blockIndex] = 2
    console.log(`Piece ${block.index} block ${blockIndex} received!`)
  }

  need (block) {
    const blockIndex = block.begin / parser.BLOCK_LEN

    return this._pieces[block.index][blockIndex] === 0
      ? true
      : this._pieces[block.index][blockIndex] === 2
        ? false
        : this._pieces.some(piece => piece.some(blockFlag => !blockFlag))
          ? false : true
  }

  finished () {
    return !this._pieces.some(piece => piece.some(blockFlag => blockFlag != 2))
  }

  progress () {
    const downloaded = this._pieces.reduce((totalReceived, blocks) => blocks.filter(blockFlag => blockFlag === 2).length + totalReceived, 0)
    const total = this._pieces.reduce((totalBlocks, blocks) => blocks.length + totalBlocks, 0)

    const percent = Math.floor(downloaded / total * 100)

    console.log(`Progress: ${percent}%.\r`)
  }
}